package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.itheima.POJO.Order;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.OrderService;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private JedisPool jedisPool;
    @Reference
    private OrderService orderService;

    @RequestMapping("/findById")
    public Result findById(Integer id){
        try {
            Map map =  orderService.findById(id);
            return  new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return  new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }

    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map){
        //获取预约的手机号
        String telephone = (String) map.get("telephone");
        //得到redis中保存的验证码
        String validateCodeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        //取出页面传过来的验证码
        String validateCode = (String) map.get("validateCode");
        //进行验证码的比对
        Result result = null;
        if(validateCodeInRedis != null  && validateCode!= null && validateCodeInRedis.equals(validateCode)){
           //比对成功
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            try {
                //调用业务层预约方法
                result = orderService.order(map);
            } catch (Exception e) {
                e.printStackTrace();
                //预约失败
                return result;
            }
//           if(result.isFlag()){//预约成功
//               //发送短息提示
//               try {
//                   SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE, telephone,(String) map.get("orderDate") );
//               } catch (ClientException e) {
//                   e.printStackTrace();
//               }
//           }
            return result;
        }else
            //比对失败，给出提示
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

}
